<?php
$post = C('post');
$openid = C('openid'); // app_init

$userService = loadService('User');
$isLoged = C('isloged', $userService->isLogedByOpenid($openid));

// 已申请过的，直接显示二维码
if($isLoged) {
	$user = $userService->getByOpenid($openid);

	// 已经核销
	if($user['codestatus']==2) message('二维码已经核销');

	$code = $userService->n2code($user['id']);
	$str = SERVER_URL.'?do=check&cpcode='.$code;
	C('QRimg', QR::createQRCode($str, $code));
	loadView();
	exit;
}

// 上限校验
$count = $userService->count();
if($count>=$userService->userLimit) {
	message('礼品已超过领取限制');
	C('isLimit', 1);
	loadView();
	exit;
}

// 提交申请
if(!empty($post)) {

	if(!isset($post['realname']) || !isset($post['mobile']) || empty($post['realname']) || empty($post['mobile'])) {
		message('姓名和手机号必须填写', SERVER_URL."?do=index", 1);
		//echo "<script>alert('姓名和手机号必须填写');location.href='".SERVER_URL."?do=index'</script>";
		//exit;
	}
	$post['openid'] = $openid;
	$id = $userService->addItem($post);
	if(!$id) exit('add user error');
	$code = $userService->n2code($id);
	$str = SERVER_URL.'?do=check&cpcode='.$code;
	C('QRimg', QR::createQRCode($str, $code));
	C('isloged', 1);
}

loadView(); // 默认加载同名
?>
